"use client";

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import dayjs from 'dayjs';

interface Transaction {
  id: string;
  hash: string;
  chain: string;
  from: string;
  to: string;
  value: string;
  valueUSD: number;
  blockNumber: number;
  timestamp: string;
  gasPrice?: string;
  gasUsed?: number;
  tokenAddress?: string;
  tokenSymbol?: string;
  tokenDecimals?: number;
  confirmed: boolean;
  fromLabel?: { type: string; label: string };
  toLabel?: { type: string; label: string };
}

interface PaginatedResponse {
  items: Transaction[];
  total: number;
  page: number;
  limit: number;
  totalPages: number;
}

const Transactions: React.FC = () => {
  const [transactions, setTransactions] = useState<Transaction[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0
  });

  // Filter conditions
  const [filters, setFilters] = useState({
    chain: '',
    minValue: '',
    maxValue: '',
    address: '',
    dateRange: null as [string, string] | null
  });

  // Fetch transaction data
  const fetchTransactions = async (page = 1, pageSize = 20) => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: page.toString(),
        limit: pageSize.toString()
      });

      // Add filter conditions
      if (filters.chain) params.append('chain', filters.chain);
      if (filters.minValue) params.append('minValue', filters.minValue);
      if (filters.maxValue) params.append('maxValue', filters.maxValue);
      if (filters.address) params.append('address', filters.address);
      if (filters.dateRange) {
        params.append('startDate', filters.dateRange[0]);
        params.append('endDate', filters.dateRange[1]);
      }

      const response = await axios.get(`/api/transactions?${params.toString()}`);
      
      if (response.data.success) {
        const data: PaginatedResponse = response.data.data;
        setTransactions(data.items);
        setPagination({
          current: data.page,
          pageSize: data.limit,
          total: data.total
        });
      }
    } catch (error) {
      console.error('Failed to fetch transaction data:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchTransactions();
  }, []);

  // Handle filter
  const handleFilter = () => {
    fetchTransactions(1, pagination.pageSize);
  };

  // Reset filters
  const handleReset = () => {
    setFilters({
      chain: '',
      minValue: '',
      maxValue: '',
      address: '',
      dateRange: null
    });
    setTimeout(() => fetchTransactions(1, pagination.pageSize), 100);
  };

  // Get explorer URL
  const getExplorerUrl = (chain: string, hash: string): string => {
    const explorers = {
      ethereum: `https://etherscan.io/tx/${hash}`,
      bsc: `https://bscscan.com/tx/${hash}`,
      polygon: `https://polygonscan.com/tx/${hash}`,
      bitcoin: `https://blockchair.com/bitcoin/transaction/${hash}`,
      base: `https://basescan.org/tx/${hash}`,
      solana: `https://solscan.io/tx/${hash}`
    };
    return explorers[chain as keyof typeof explorers] || '#';
  };

  const getChainColor = (chain: string) => {
    const colors: Record<string, string> = {
      ethereum: 'bg-blue-500',
      bsc: 'bg-yellow-500',
      bitcoin: 'bg-orange-500',
      base: 'bg-cyan-500',
      solana: 'bg-purple-500',
      polygon: 'bg-purple-600'
    };
    return colors[chain] || 'bg-green-500';
  };

  const getLabelColor = (type: string) => {
    const colors: Record<string, string> = {
      exchange: 'bg-blue-500',
      whale: 'bg-purple-500',
      defi: 'bg-green-500',
      bridge: 'bg-orange-500'
    };
    return colors[type] || 'bg-gray-500';
  };

  const totalPages = Math.ceil(pagination.total / pagination.pageSize);

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Transaction History</h1>
        <p className="text-gray-600 dark:text-gray-400">
          View all monitored large transfer records
        </p>
      </div>

      {/* Statistics Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <div className="bg-white dark:bg-zinc-800 shadow-sm rounded-lg p-4">
          <h3 className="text-sm font-medium text-gray-500 dark:text-gray-400">Total Transactions</h3>
          <p className="text-2xl font-bold text-blue-400 mt-2">
            {pagination.total}
          </p>
        </div>
        <div className="bg-white dark:bg-zinc-800 shadow-sm rounded-lg p-4">
          <h3 className="text-sm font-medium text-gray-500 dark:text-gray-400">Current Page</h3>
          <p className="text-2xl font-bold text-green-400 mt-2">
            {pagination.current}/{totalPages}
          </p>
        </div>
        <div className="bg-white dark:bg-zinc-800 shadow-sm rounded-lg p-4">
          <h3 className="text-sm font-medium text-gray-500 dark:text-gray-400">Page Size</h3>
          <p className="text-2xl font-bold text-yellow-400 mt-2">
            {pagination.pageSize}
          </p>
        </div>
      </div>

      {/* Filter Area */}
      <div className="bg-white dark:bg-zinc-800 shadow-sm rounded-lg p-4">
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-500 dark:text-gray-400 mb-2">
              Blockchain
            </label>
            <select
              value={filters.chain}
              onChange={(e) => setFilters({...filters, chain: e.target.value})}
              className="w-full px-4 py-2 pr-10 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-zinc-700 dark:text-white"
            >
              <option value="">All Chains</option>
              <option value="ethereum">Ethereum</option>
              <option value="bsc">Binance Smart Chain</option>
              <option value="bitcoin">Bitcoin</option>
              <option value="base">Base</option>
              <option value="solana">Solana</option>
              <option value="polygon">Polygon</option>
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Min Amount ($)
            </label>
            <input
              type="text"
              placeholder="Min amount"
              value={filters.minValue}
              onChange={(e) => setFilters(prev => ({ ...prev, minValue: e.target.value }))}
              className="w-full px-4 py-2 pr-10 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-zinc-700 dark:text-white"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Max Amount ($)
            </label>
            <input
              type="text"
              placeholder="Max amount"
              value={filters.maxValue}
              onChange={(e) => setFilters(prev => ({ ...prev, maxValue: e.target.value }))}
              className="w-full px-4 py-2 pr-10 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-zinc-700 dark:text-white"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-500 dark:text-gray-400 mb-2">
              Search Address
            </label>
            <input
              type="text"
              placeholder="Address"
              value={filters.address}
              onChange={(e) => setFilters(prev => ({ ...prev, address: e.target.value }))}
              className="w-full px-4 py-2 pr-10 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-zinc-700 dark:text-white"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Actions
            </label>
            <div className="flex gap-2">
              <button 
                onClick={handleFilter}
                className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2"
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                </svg>
                Filter
              </button>
              <button 
                onClick={handleReset}
                className="px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 flex items-center gap-2"
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                </svg>
                Reset
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Transaction Table */}
      <div className="bg-white dark:bg-zinc-800 shadow-sm rounded-lg">
        <div className="p-6 border-b border-gray-200 dark:border-gray-700">
          <div className="flex justify-between items-center">
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white">Transaction List</h3>
            <div className="flex gap-2">
              <button 
                onClick={() => fetchTransactions(pagination.current, pagination.pageSize)}
                disabled={loading}
                className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 flex items-center gap-2"
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                </svg>
                Refresh
              </button>
              <button 
                onClick={() => console.log('Export functionality under development')}
                className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 flex items-center gap-2"
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                </svg>
                Export
              </button>
            </div>
          </div>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50 dark:bg-zinc-700">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                  Chain
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                  Transaction Hash
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                  From
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                  To
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                  Amount
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                  Block
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                  Time
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                  Status
                </th>
              </tr>
            </thead>
            <tbody className="bg-white dark:bg-zinc-800 divide-y divide-gray-200 dark:divide-gray-700">
              {loading ? (
                <tr>
                  <td colSpan={8} className="px-6 py-4 text-center">
                    <div className="flex justify-center items-center">
                      <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"></div>
                      <span className="ml-2 text-gray-500 dark:text-gray-400">Loading...</span>
                    </div>
                  </td>
                </tr>
              ) : transactions && transactions.length > 0 ? (
                transactions.map((tx) => (
                  <tr key={tx.id} className="hover:bg-gray-50 dark:hover:bg-zinc-700 transition-colors">
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className={`px-3 py-1 text-xs font-medium text-white rounded-full ${getChainColor(tx.chain)}`}>
                        {tx.chain.toUpperCase()}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <a 
                        href={getExplorerUrl(tx.chain, tx.hash)} 
                        target="_blank" 
                        rel="noopener noreferrer"
                        className="text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 font-mono text-sm"
                      >
                        {tx.hash.substring(0, 10)}...{tx.hash.substring(tx.hash.length - 8)}
                      </a>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div>
                        {tx.from === 'COINBASE' ? (
                          <span className="inline-block px-3 py-1 text-xs font-bold bg-yellow-500 text-white rounded-full">
                            COINBASE
                          </span>
                        ) : (
                          <>
                            <div className="font-mono text-sm text-gray-900 dark:text-gray-300">
                              {tx.from.substring(0, 6)}...{tx.from.substring(tx.from.length - 4)}
                            </div>
                            {tx.fromLabel && (
                              <span className={`inline-block px-2 py-1 text-xs font-medium text-white rounded-full mt-1 ${getLabelColor(tx.fromLabel.type)}`}>
                                {tx.fromLabel.label}
                              </span>
                            )}
                          </>
                        )}
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div>
                        <div className="font-mono text-sm text-gray-900 dark:text-gray-300">
                          {tx.to.substring(0, 6)}...{tx.to.substring(tx.to.length - 4)}
                        </div>
                        {tx.toLabel && (
                          <span className={`inline-block px-2 py-1 text-xs font-medium text-white rounded-full mt-1 ${getLabelColor(tx.toLabel.type)}`}>
                            {tx.toLabel.label}
                          </span>
                        )}
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div>
                        <div className="text-lg font-semibold text-green-400">
                          ${tx.valueUSD.toLocaleString()}
                        </div>
                        {tx.tokenSymbol && (
                          <div className="text-sm text-gray-500 dark:text-gray-400">
                            {parseFloat(tx.value).toFixed(4)} {tx.tokenSymbol}
                          </div>
                        )}
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-300">
                      {tx.blockNumber.toLocaleString()}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div>
                        <div className="text-sm text-gray-900 dark:text-gray-300">
                          {dayjs(tx.timestamp).format('MM-DD')}
                        </div>
                        <div className="text-sm text-gray-500 dark:text-gray-400">
                          {dayjs(tx.timestamp).format('HH:mm:ss')}
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className={`px-2 py-1 text-xs font-medium rounded ${
                        tx.confirmed 
                          ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200' 
                          : 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200'
                      }`}>
                        {tx.confirmed ? 'Confirmed' : 'Pending'}
                      </span>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={8} className="px-6 py-4 text-center text-gray-500 dark:text-gray-400">
                    No transaction data available
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        <div className="px-6 py-4 border-t border-gray-200 dark:border-gray-700">
          <div className="flex items-center justify-between">
            <div className="text-sm text-gray-700 dark:text-gray-300">
              Showing {((pagination.current - 1) * pagination.pageSize) + 1} to{' '}
              {Math.min(pagination.current * pagination.pageSize, pagination.total)} of{' '}
              {pagination.total} results
            </div>
            <div className="flex gap-2">
              <button
                onClick={() => fetchTransactions(pagination.current - 1, pagination.pageSize)}
                disabled={pagination.current <= 1 || loading}
                className="px-3 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed dark:bg-zinc-700 dark:border-gray-600 dark:text-gray-400 dark:hover:bg-zinc-600 transition-colors"
              >
                Previous
              </button>
              <span className="px-3 py-2 text-sm font-medium text-gray-700 bg-gray-50 border border-gray-300 rounded-lg dark:bg-zinc-600 dark:border-gray-600 dark:text-gray-300">
                Page {pagination.current} of {totalPages}
              </span>
              <button
                onClick={() => fetchTransactions(pagination.current + 1, pagination.pageSize)}
                disabled={pagination.current >= totalPages || loading}
                className="px-3 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed dark:bg-zinc-700 dark:border-gray-600 dark:text-gray-400 dark:hover:bg-zinc-600 transition-colors"
              >
                Next
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Transactions; 